//引入模块
// import cheerio from "cheerio";
// import https from "https";
// import fs from "fs";
const https = require('https')
const cheerio = require('cheerio')
const fs = require('fs')
const xlsx = require('xlsx');

//获取页面的html结构
https.get('https://movie.douban.com/top250', function (res) {
    let html = ''
    res.on('data', function (chunk) {
        //console.log(chunk + '');
        html += chunk
    })
    res.on('end', function () {
        // 获取html中的数据
        const $ = cheerio.load(html)
        let allFiles = []
        //拿到每一个item中我们需要的数据
        $('li .item').each(function () {
            const title = $('.title', this).text()
            const star = $('.info .bd .rating_num', this).text()
            const pic = $('.pic img', this).attr('src')
            //数据以对象的形式存放在数组中
            allFiles.push({
                title: title, star: star, pic: pic
            })
        })
        let arr2 = allFiles.map(obj => [obj.title, obj.star, obj.pic]);
        arr2 = [["title","star","pic"],...arr2]
        console.log(arr2);
        //将数据写入文件中
        const worksheet = xlsx.utils.aoa_to_sheet(arr2);
        const workbook = xlsx.utils.book_new();
        xlsx.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        xlsx.writeFile(workbook, 'test.xlsx');
        console.log('文件保存成功');
    })
})